package modelz;

import java.util.Iterator;
import java.util.SortedMap;
import java.util.TreeMap;

/**
 * A Map that contains and managed IdHolders.
 *
 * @author mkl
 */
public class IdMap<S extends Comparable< ? super S>, T extends IdHolder<S, T>>
		extends UpdateableCollection<T> {

	public IdMap(ObjectFactory client) {
		super(client);
	}

	protected final SortedMap<S, T> items = new TreeMap<S, T>();

	public T find(S id) {
		if (id == null)
			throw new NullPointerException();
		return items.get(id);
	}

	public T create(Class<T> c, S id) throws InstantiationException {
		T item = createInstance(c);
		item.setId(id);
		items.put(id, item);
		return item;
	}

	protected void performRemove(T item) {
		if (item == null)
			return;
		items.remove(item.getId());
	}

	public void remove(S id) {
		if (id == null)
			throw new NullPointerException();
		remove(items.get(id));
	}

	public int size() {
		return items.size();
	}

	public Iterator<T> iterator() {
		return items.values().iterator();
	}

	protected void performClear() {
		items.clear();
	}

}
